/**
 * Java RTP Library (jlibrtp)
 * Copyright (C) 2006 Arne Kepp
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
package com.detrum.detrumdata.jlibrtp;

import static com.detrum.base.BaseStatic.savaInfoToSD;

/**
 * A PktBuffer stores packets either for buffering purposes,
 * or because they need to be assimilated to create a complete frame.
 * 
 * This behavior can be controlled through rtpSession.pktBufBehavior()
 * 
 * It optionally drops duplicate packets.
 * 
 * Note that newest is the most recently received, i.e. highest timeStamp
 * Next means new to old (from recently received to previously received) 
 * 
 * @author Arne Kepp
 */

public class PktBuffer {

	/** The RTPSession holds information common to all packetBuffers, such as max size */
	final int MAX_FRAME_LIST_LEN = 3;
	/** The length of the buffer */
	int length = 0;

	/** Frame list, timestamp  ascending order */
    FrameNode frameList = null;
	
	/** The last sequence number received */
	long minTimestamp = 0x100000000L;
	/** The last timestamp */
	long maxTimestamp = -1;

	public PktBuffer() {
		frameList = null;
		length = 0;

		minTimestamp = 0x100000000L;
		maxTimestamp = -1;
	}

	/**
	 * Adds a packet, this happens in constant time if they arrive in order.
	 * Optimized for the case where each pkt is a complete frame.
	 * 
	 * @param aPkt the packet to be added to the buffer.
	 * @return integer, negative if operation failed (see code)
	 */
	public synchronized int addPkt(RtpPkt aPkt) {
        PktBufNode newNode = new PktBufNode(aPkt);
		//savaInfoToSD("Got New RTP Packet: ts=" + newNode.timeStamp + " seq=" + newNode.seqNum + " len=" + newNode.len );
        return bufferedAddPkt(newNode);
	}

	private void updateTimestamp(long timestamp){
		if( timestamp < minTimestamp )
			minTimestamp = timestamp;

		if( timestamp > maxTimestamp )
			maxTimestamp = timestamp ;
	}

	private int drop_oldest_frame(){
        FrameNode tmpnode = frameList;

        //timestamp 回绕
        if( (minTimestamp == 0) && (maxTimestamp == 0xFFFFFFFFL) )
		{
			while(tmpnode!=null)
			{
				if(tmpnode.nextFrame != null)
				{
					if(tmpnode.timeStamp + 1 != tmpnode.nextFrame.timeStamp)
					{
						tmpnode = tmpnode.nextFrame;
						break;
					}
					continue;
				}
				else
				{
					//the last one in list
					break;
				}
			}
		}
		else
		{
			frameList = tmpnode.nextFrame;
        }

        length --;

		savaInfoToSD("drop_oldest_frame: ts= " + tmpnode.timeStamp  + " pkg count=" + tmpnode.pktCount + " curlen=" +  tmpnode.len);
        return 0;
    }

	/**
	 * Does most of the packet organization for the application.
	 * Packets are put in order, duplicate packets or late arrivals are discarded
	 * 
	 * If multiple packets make up a frame, these will also be organized
	 * by RTP timestamp and sequence number, and returned as a complete frame.
	 * 
	 * @param newNode the node to add to the packet buffer
	 * @return 0 if everything is okay, -1 otherwise
	 */
	private int bufferedAddPkt(PktBufNode newNode) {

        FrameNode newFrame = null;
		if(length == 0) {
            newFrame = new FrameNode(newNode.timeStamp, newNode.PayloadType);

			// The buffer was empty, this packet is the one and only.
			frameList = newFrame;
			length ++;
			updateTimestamp(newNode.timeStamp);

            return newFrame.addPktToFrame(newNode);
		}

		FrameNode tmpNode = frameList;
		FrameNode lastNode = null;
		while(tmpNode != null) {
			if(newNode.timeStamp < tmpNode.timeStamp) {
				break;
			}
			else if( tmpNode.timeStamp == newNode.timeStamp ) {
				//Packet has same timestamp, presumably belongs to frame. Need to order within frame.
				return tmpNode.addPktToFrame(newNode);
			}

			lastNode = tmpNode;
			tmpNode = lastNode.nextFrame;
		}

		//insert before tmpNode, after lastNode
		newFrame = new FrameNode(newNode.timeStamp,newNode.PayloadType);

		if(tmpNode == null)
		{
			//add at last
			newFrame.prevFrame = lastNode;
			lastNode.nextFrame = newFrame;
		}
		else
		{
			if( lastNode == null )
			{
				// add at first
				newFrame.nextFrame = tmpNode;
				tmpNode.prevFrame = newFrame;

				frameList = newFrame;
			}
			else
			{
				newFrame.nextFrame = tmpNode;
				newFrame.prevFrame = lastNode;
				tmpNode.prevFrame = newFrame;
				lastNode.nextFrame = newFrame;
			}
		}

        length++;
        return newFrame.addPktToFrame(newNode);

	}

	/** 
	 * Checks the oldest frame, if there is one, sees whether it is complete.
	 * @return Returns null if there are no complete frames available.
	 */
	public synchronized FrameNode popOldestFrame() {
		return this.bufferedPopFrame();
	}

	/**
	 * Only returns if the buffer is full, i.e. length exceeds
	 * rtpSession.pktBufBehavior, or if the next packet directly
	 * follows the previous one returned to the application.
	 * 
	 * @return first frame in order, null otherwise
	 */
	private FrameNode bufferedPopFrame() {
		FrameNode frameNode = frameList;
		/**
		 * Three scenarios:
		 * 1) There are no packets available
		 * 2) The first packet is vailable and in order
		 * 3) The first packet is not the next on in the sequence
		 * 		a) We have exceeded the wait buffer
		 * 		b) We wait
		 */
		//System.out.println(" Debug:" +(retNode != null) + " " + (retNode.seqNum == this.lastSeqNumber + 1)
		//		+ " " + ( retNode.seqNum == 0 ) + " " +  (this.length > this.rtpSession.maxReorderBuffer)
		//		+ " " + (this.lastSeqNumber < 0));

		// Pop it off, null all references.
        while(frameNode !=null ){
            if( !frameNode.isComplete) {
                popFrameCleanup(frameNode);
				//savaInfoToSD("bufferedPopFrame: ts= " + frameNode.timeStamp  + " pkg count=" + frameNode.pktCount + " curlen=" +  frameNode.len);
                return frameNode;
            }
            frameNode = frameNode.nextFrame;
        }

		return null;
	}
	
	/**
	 * Cleans the packet buffer before returning the frame,
	 * i.e. making sure the queue has a head etc.
	 */
	private void popFrameCleanup(FrameNode frameNode) {
		if(1 == length) {
			//There's only one frame
			frameList = null;
		} else {
			//There are more frame
			if( frameNode.prevFrame != null)
				frameNode.prevFrame.nextFrame = frameNode.nextFrame;
			if( frameNode.nextFrame != null)
				frameNode.nextFrame.prevFrame = frameNode.prevFrame;
		}

		// Update counters
		length--;
	}
	
	/** 
	 * Returns the length of the packetbuffer.
	 * @return number of frames (complete or not) in packetbuffer.
	 */
	protected int getLength() {
		return length;
	}
}
